package com.eclink.asset.consume.service;


import cn.hutool.core.lang.generator.SnowflakeGenerator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eclink.asset.consume.convert.ConsumeInventoryCheckConvert;
import com.eclink.asset.consume.domain.dao.ConsumeInventory;
import com.eclink.asset.consume.domain.dao.ConsumeInventoryCheck;
import com.eclink.asset.consume.domain.dao.ConsumeInventoryCheckRelItem;
import com.eclink.asset.consume.domain.query.ConsumeInventoryCheckAddQuery;
import com.eclink.asset.consume.domain.query.ConsumeInventoryCheckAddQueryBaseForm;
import com.eclink.asset.consume.domain.query.ConsumeInventoryCheckAddQueryRangeForm;

import com.eclink.asset.consume.mapper.ConsumeInventoryCheckMapper;
import com.eclink.asset.consume.mapper.ConsumeInventoryCheckRelItemMapper;


import com.eclink.asset.domain.dto.*;
import com.eclink.asset.domain.query.AssetInventoryQuery;
import com.eclink.asset.enums.AssetInventoryItemResultEnum;
import com.eclink.asset.enums.AssetInventoryStateEnum;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 耗材盘点服务
 *
 *
 * @author zcc
 */
@Service
public class ConsumeInventoryCheckService {

    @Resource
    private SnowflakeGenerator idGenerator;

    @Resource
    private ConsumeInventoryCheckMapper consumeInventoryCheckMapper;

    @Resource
    private ConsumeInventoryCheckRelItemMapper consumeInventoryCheckRelItemMapper;

    @Resource
    private ConsumeInventoryCheckConvert convert;

    @Resource
    private ConsumeInventoryService consumeInventoryService;

    @Resource
    private ConsumeWarehouseService consumeWarehouseService;


    private static final String APPLY_TYPE = "HCPD";

    private String getFormatNumber(int num, String parentNumber) {
        String pre = "0000";
        int preLength = pre.length();
        String str = pre + num;
        int strLength = str.length();
        String formatStr = str.substring(strLength - preLength, strLength);
        return StringUtils.isBlank(parentNumber) ? formatStr : parentNumber + "-" + formatStr;
    }

    public String getLastNumberFormat(Integer parentId, String parentNumber) {
        int lastNumber = this.getLastNumber(parentId);
        return this.getFormatNumber(lastNumber+1, parentNumber);
    }

    private int getLastNumber(Integer parentId) {
        QueryWrapper<ConsumeInventoryCheck> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);

        if (parentId == null) {
            parentId = 0;
        }

        // 根据父节点查询
        qw.eq("parent_id", parentId);
        qw.last("limit 1");
        qw.orderByDesc("number");
        int num = 0;

        List<ConsumeInventoryCheck> list = consumeInventoryCheckMapper.selectList(qw);
        if (list == null || list.isEmpty()) {
            return num;
        }
        ConsumeInventoryCheck one = list.get(0);
        String number = one.getNumber();
        String[] numberArr = number.split("-");
        String numberLast = numberArr[numberArr.length-1];
        return Integer.parseInt(numberLast);

    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return 资产分类表
     */
    public ConsumeInventoryCheck selectById(Long id) {
        return consumeInventoryCheckMapper.selectById(id);
    }



    /**
     * 查询列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 资产分类表
     */
    public List<ConsumeInventoryCheck> selectList(AssetInventoryQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        QueryWrapper<ConsumeInventoryCheck> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);
        qw.orderByDesc("id");

        String number = query.getNumber();
        if (!StringUtils.isEmpty(number)) {
            qw.like("number", number);
        }
        if (StringUtils.isNotBlank(query.getValue())) {
            qw.like(query.getField(), query.getValue());
        }
        return consumeInventoryCheckMapper.selectList(qw);
    }

    /**
     * 查询资产分类表列表
     *
     * @return 资产分类表
     */
    public List<ConsumeInventoryCheck> selectListAll() {

        QueryWrapper<ConsumeInventoryCheck> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);
        return consumeInventoryCheckMapper.selectList(qw);
    }

    /**
     * 编号后缀的长度 如：000001, 000002.....999999，则长度为6
     */
    private static final int NUMBER_APPEND_LENGTH = 6;

    private String getInApplyNumber(String applyType) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String numberPrefix = applyType + sdf.format(new Date(System.currentTimeMillis()));

        // 查询出最后一项的编号
        QueryWrapper<ConsumeInventoryCheck> qw = new QueryWrapper<>();
        qw.likeRight("number", numberPrefix);
        qw.last("limit 1");
        qw.orderByDesc("number");
        ConsumeInventoryCheck lastOne = consumeInventoryCheckMapper.selectOne(qw);
        int orderNo = 1;

        if (lastOne != null) {
            String lastNumber = lastOne.getNumber();
            int numberLength = lastNumber.length();
            orderNo = Integer.parseInt(lastNumber.substring(numberLength - NUMBER_APPEND_LENGTH, numberLength)) + 1;
        }
        String numberAppend = "000000" + orderNo;
        numberAppend = numberAppend.substring(numberAppend.length() - NUMBER_APPEND_LENGTH);

        return numberPrefix + numberAppend;
    }


    private BigDecimal getTotalPrice(Integer num, BigDecimal price) {
        return price.multiply(BigDecimal.valueOf(num));
    }

    @Transactional
    public void save(ConsumeInventoryCheckAddQuery query) {

        ConsumeInventoryCheck assetInventory = new ConsumeInventoryCheck();
        ConsumeInventoryCheckAddQueryBaseForm baseForm = query.getBaseForm();
        ConsumeInventoryCheckAddQueryRangeForm rangeForm = query.getRangeForm();
        List<ConsumeInventory> list = consumeInventoryService.getInventoryBatchList(rangeForm);

        String id = String.valueOf(idGenerator.next());
        assetInventory.setId(id);
        // 获取入库流程的配置
        assetInventory.setNumber(this.getInApplyNumber(APPLY_TYPE));
        assetInventory.setNum(list.size());
        assetInventory.setTitle(baseForm.getTitle());

        assetInventory.setResultCode(AssetInventoryItemResultEnum.DRAFT.getValue());

        // 插入inApply表
        consumeInventoryCheckMapper.insert(assetInventory);

        for(ConsumeInventory item : list) {
            BeanUtils.copyProperties(item, assetInventory);
            ConsumeInventoryCheckRelItem relItem = new ConsumeInventoryCheckRelItem();
            BeanUtils.copyProperties(item, relItem);
            relItem.setNum(item.getNum());
            if (relItem.getWarehouseId()!=null) {
                relItem.setWarehouseName(consumeWarehouseService.getWarehouseNameById(relItem.getWarehouseId()));
            }
            relItem.setTotalPrice(getTotalPrice(item.getNum(), item.getPrice()));
            relItem.setParentId(id);
            relItem.setState(AssetInventoryItemResultEnum.DRAFT.getValue());
            consumeInventoryCheckRelItemMapper.insert(relItem);
        }
    }


    public ConsumeInventoryCheck getById(String id) {
        return consumeInventoryCheckMapper.selectById(id);
    }

    public List<ConsumeInventoryCheckRelItem> getItemsById(String id) {
        QueryWrapper<ConsumeInventoryCheckRelItem> qw = new QueryWrapper<>();
        qw.eq("parent_id", id);
        return consumeInventoryCheckRelItemMapper.selectList(qw);
    }

    /**
     * 详情
     * @param id ID
     *
     */
    public ConsumeInventoryCheck getDetailById(String id) {
        return getById(id);

    }

    public List<ConsumeInventoryCheckRelItem> getDetailRelItems(String id) {
        return getItemsById(id);
    }


    /**
     * 删除
     * @param ids IDs
     *
     */
    public void deleteByIds(Long[] ids) {
        for(Long id : ids) {

            consumeInventoryCheckMapper.deleteById(id);

            QueryWrapper<ConsumeInventoryCheckRelItem> qw = new QueryWrapper<>();
            qw.eq("parent_id", id);
            consumeInventoryCheckRelItemMapper.delete(qw);
        }

    }

    public List<DistributeItem> getTipContent(String id) {
        return consumeInventoryCheckMapper.getTipContent(id);
    }

}
